//
//  LinkedListNode.swift
//  SwiftyDSA
//
//  Created by Archer on 2018/8/5.
//  Copyright © 2018年 Archer. All rights reserved.
//

import Foundation

/// 注意前驱和后继节点的相对性
/// 使用weak避免循环引用
public final class LinkedListNode<Element> {
    
    /// 数据域
    var value: Element?
    /// 后继节点
    var successor: LinkedListNode<Element>?
    /// 前驱节点
    weak var predecessor: LinkedListNode<Element>?
    
    /// 初始化一个节点
    /// 当作为header和trailer存在时，只是作为哨兵节点
    /// 此时数据域是没有意义的
    ///
    /// - Parameter val: 当前节点的数据域
    init(val: Element? = nil) {
        value = val
        successor = nil
        predecessor = nil
    }
    
    /// 作为当前节点的后继节点插入
    func insertAsSuccessor(_ val: Element) {
        let node = LinkedListNode(val: val)
        successor?.predecessor = node
        node.successor = successor
        node.predecessor = self
        successor = node
    }
    
    /// 作为当前节点的前驱节点插入
    func insertAsPredecessor(_ val: Element) {
        let node = LinkedListNode(val: val)
        predecessor?.successor = node
        node.predecessor = predecessor
        node.successor = self
        predecessor = node
    }
    
    deinit { debugPrint(String(format: "\(self) = %p is deinitializing", UInt(bitPattern: ObjectIdentifier(self)))) }
}

extension LinkedListNode: CustomStringConvertible {
    public var description: String {
        return "LinkedListNodeValue = " + String(describing: value)
    }
}

extension LinkedListNode: Equatable where Element: Equatable {
    public static func == (lhs: LinkedListNode<Element>, rhs: LinkedListNode<Element>) -> Bool {
        return lhs.value == rhs.value
    }
}

extension LinkedListNode: Comparable where Element: Comparable {
    public static func < (lhs: LinkedListNode<Element>, rhs: LinkedListNode<Element>) -> Bool {
        // only _header && _trailer 's value scope can be nil
        guard let lval = lhs.value, let rval = rhs.value else { fatalError("header/trailer参与了比较") }
        return lval < rval
    }
}
